/* eslint-disable no-param-reassign */
import DrawerFooter from '@/components/DrawerFooter';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Icon, Input, ResponsiveGrid, Switch, DatePicker } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, model, column, ENUMS, toSelectDataSource, DATETIME_TEXT } from '../stores/definitions';
import AttachmentForm from './AttachmentForm';
import QR from '@/components/QR/QR';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

function ChannelForm({ channelId, modal, onSubmit, onCancel }) {
  const { channelStore: store } = useStore();
  const [channel] = useState(() => observable({}));
  const [QRModal, setQRModal] = useState({});
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  const isCompany = channel.independentAccount?.collectionAccountInformation?.type === 'MERCHANT_ID';
  const isPrice = channel.independentAccount?.independentAccountType === '1';

  const cc = channel?.discountInfo?.cc?.type === '1';
  const bus = channel?.discountInfo?.bus?.type === '1';
  const sc = channel?.discountInfo?.sc?.type === '1';
  const rs = channel?.discountInfo?.rs?.type === '1';

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    independentAccount: {
      collectionAccountInformation: {
        name: {
          label: isCompany ? t`公司名称` : t`真实姓名`,
          ui: {
            itemProps: { required: isCompany },
          },
        },
        accountIdentification: {
          label: isCompany ? t`公司商户号` : t`账号标识`,
          ui: {
            renderer: (v) => (<Input
              value={v}
              readOnly={!isCompany}
              // disabled={!isCompany}
              placeholder={isCompany ? t`请填写公司商户号` : t`请扫码绑定收款帐号`}
              addonAfter={isCompany || isViewMode ? null : <Button type="primary" onClick={handleQrCode}>{t`扫码设置`}</Button>}
            />),
            itemProps: { required: isCompany },
          },
        },
      },
      acceptorType: {
        label: t`分账对象`,
        ui: {
          renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.acceptorType)} value={v} />,
          itemProps: { required: true },
        },
      },
      independentAccountType: {
        label: t`分账收款类型`,
        ui: {
          renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.independentAccountType)} value={v} />,
        },
      },
      independentAccountValue: {
        label: isPrice ? t`分账金额` : t`分账比例`,
        RMB: {
          label: isPrice ? t`分账金额` : t`分账比例`,
        },
      },
      viewAcceptorType: {
        label: t`分账对象`,
        ui: {
          renderer: (v) => <Input readOnly value={ENUMS.acceptorType[v]} />,
        },
      },
      viewIndependentAccountType: {
        label: t`分账收款类型`,
        ui: {
          renderer: (v) => <Input readOnly value={ENUMS.independentAccountType[v]} />,
        },
      },
      viewIndependentAccountValue: {
        label: isPrice ? t`分账金额` : t`分账比例`,
        RMB: {
          label: isPrice ? t`分账金额` : t`分账比例`,
          ui: {
            renderer: (v) => <Input readOnly value={v} />,
          },
        },
      },
    },
    mobile: {
      label: t`手机号`,
      ui: {
        renderer: (v) => <Input value={v} readOnly={modal[0] === 'edit'} />,
        itemProps: { required: true },
      },
    },
    discountInfo: {
      label: t`分佣信息`,
      disable: {
        label: t`是否启用`,
        ui: {
          renderer: (v) => {
            return (<Switch
              checked={v}
              size="small"
              autoWidth
              checkedChildren="是"
              unCheckedChildren="否"
            />);
          },
        },
      },
      failureTime: {
        label: t`失效时间`,
        text: DATETIME_TEXT,
        ui: {
          renderer: (v) => <DatePicker type="datetime" showTime value={v} />,
        },
      },
      bus: {
        label: t`巴士分佣信息`,
        type: {
          label: t`巴士分佣类型`,
          ui: {
            renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
          },
        },
        discountValue: {
          label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
          '{RMB}': {
            label: bus ? t`巴士分佣值[key]` : t`巴士分佣比例`,
          },
        },
      },
      cc: {
        label: t`包车分佣信息`,
        type: {
          label: t`包车分佣类型`,
          ui: {
            renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
          },
        },
        discountValue: {
          label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
          '{RMB}': {
            label: cc ? t`包车分佣值[key]` : t`包车分佣比例`,
          },
        },
      },
      sc: {
        label: t`专线分佣信息`,
        type: {
          label: t`专线分佣类型`,
          ui: {
            renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
          },
        },
        discountValue: {
          label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
          '{RMB}': {
            label: sc ? t`专线分佣值[key]` : t`专线分佣比例`,
          },
        },
      },
      rs: {
        label: t`拼车分佣信息`,
        type: {
          label: t`拼车分佣类型`,
          ui: {
            renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
          },
        },
        discountValue: {
          label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
          '{RMB}': {
            label: rs ? t`拼车分佣值[key]` : t`拼车分佣比例`,
          },
        },
      },
    },
  };

  useEffect(() => {
    (async () => {
      await store.getDicts('channelType');
    })();
    if (channelId) {
      (async () => {
        const data = await store.get(channelId);
        // if (data.discountInfo?.failureTime) {
        //   // eslint-disable-next-line no-param-reassign
        //   data.discountInfo.failureTime = moment(data.discountInfo?.failureTime).format('YYYY-MM-DD HH:mm');
        // }
        editCtx.origin = _.cloneDeep(data);
        _.assign(channel, data);
        const type = channel.independentAccount.acceptorType === '1' ? '0' : '1';
        _.set(channel, 'independentAccount.viewAcceptorType', type);
        _.set(channel, 'independentAccount.viewIndependentAccountType', channel.independentAccount?.independentAccountType);
        let price = '';
        if (channel.independentAccount.independentAccountType === '0') {
          price = 1 - Number(channel.independentAccount?.independentAccountValue?.RMB);
        } else {
          price = '剩余毛利';
        }
        _.set(channel, 'independentAccount.viewIndependentAccountValue.RMB', price);
        _.set(channel, 'independentAccount.suspensionOfDistribution', !data?.independentAccount?.suspensionOfDistribution);
        _.set(channel, 'discountInfo.disable', !data?.discountInfo?.disable);
      })();
    } else {
      _.set(channel, 'independentAccount.period', 0);
    }
  }, []);

  if (!channel) return <></>;

  // TODO 弹出二维码
  const handleQrCode = async () => {
    const { name } = channel;
    try {
      const baseUrl = await store.addProfitShare(channel);
      setQRModal({
        open: true,
        name,
        okText: '下载',
        onCancel: QROnCancel,
        baseUrl,
      });
    } catch (error) {
      console.log('🚀 _ file: ChannelForm.jsx:239 _ error:', error);
    }
  };

  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(channel, name, value);
    // 联动效果可以在这里通过设置channel属性实现
    if (name === 'independentAccount.collectionAccountInformation.type') {
      _.unset(channel, 'independentAccount.collectionAccountInformation.name');
      _.unset(channel, 'independentAccount.collectionAccountInformation.accountIdentification');
    }
    if (name === 'independentAccount.acceptorType') {
      const type = (value === '1' ? '0' : '1');
      _.set(channel, 'independentAccount.viewAcceptorType', type);
    }
    if (name === 'independentAccount.independentAccountType') {
      _.set(channel, 'independentAccount.viewIndependentAccountType', value);
    }
    if (name === 'discountInfo.cc.discountValue.RMB') {
      _.set(channel, 'discountInfo.cc.discountValue.HKD', value);
      _.set(channel, 'discountInfo.cc.discountValue.MOP', value);
    }
    if (name === 'discountInfo.bus.discountValue.RMB') {
      _.set(channel, 'discountInfo.bus.discountValue.HKD', value);
      _.set(channel, 'discountInfo.bus.discountValue.MOP', value);
    }
    if (name === 'discountInfo.sc.discountValue.RMB') {
      _.set(channel, 'discountInfo.sc.discountValue.HKD', value);
      _.set(channel, 'discountInfo.sc.discountValue.MOP', value);
    }
    if (name === 'discountInfo.rs.discountValue.RMB') {
      _.set(channel, 'discountInfo.rs.discountValue.HKD', value);
      _.set(channel, 'discountInfo.rs.discountValue.MOP', value);
    }
    if (name === 'independentAccount.independentAccountValue.RMB') {
      let price = '';
      if (channel.independentAccount.independentAccountType === '0') {
        price = 1 - Number(value);
      } else {
        price = '剩余毛利';
      }
      _.set(channel, 'independentAccount.viewIndependentAccountValue.RMB', price);
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(channel));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ChannelForm.jsx:307 _ errors:', errors);
      return;
    }
    _.set(channel, 'independentAccount.suspensionOfDistribution', !channel?.independentAccount?.suspensionOfDistribution);
    _.set(channel, 'discountInfo.disable', !channel?.discountInfo?.disable);
    onSubmit?.(channel);
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={channel}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['name', 'type', 'creditCode', 'address', 'mobile', 'appointCompanies']}
      />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['bindingPeriod', 'bindingPeriodExplain']}
      />
      <TitleGrid title={t`分账信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['period'].map((n) => `independentAccount.${n}`).concat(['type', 'name', 'accountIdentification'].map((n) => `independentAccount.collectionAccountInformation.${n}`))}
      />
      <TitleGrid title={t`H5包车分帐`} />
      <FieldsGrid
        formData={channel}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['acceptorType', 'independentAccountType', 'independentAccountValue.RMB'].map((n) => `independentAccount.${n}`).concat(['independentAccount.suspensionOfDistribution'])}
      />
      <FieldsGrid
        formData={channel}
        overrideModel={overrideModel}
        mode={'view'}
        fields={['viewAcceptorType', 'viewIndependentAccountType', 'viewIndependentAccountValue.RMB'].map((n) => `independentAccount.${n}`)}
      />
      <TitleGrid title={t`微信小程序分佣金`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['cc.type', 'cc.discountValue.{RMB}', 'sc.type', 'sc.discountValue.{RMB}', 'bus.type', 'bus.discountValue.{RMB}', 'rs.type', 'rs.discountValue.{RMB}', 'disable'].map((n) => `discountInfo.${n}`)}
      />
      <TitleGrid title={t`负责人信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        fields={['principalName', 'certificateType', 'idNumber', 'principalMobile'].map((n) => `principalInfo.${n}`)}
      />
      <TitleGrid title={t`银行信息`} />
      <FieldsGrid
        formData={channel}
        mode={modal[0]}
        // columns={3}
        fields={['{RMB}.bank', '{RMB}.account', '{RMB}.accountName',
          '{HKD}.bank', '{HKD}.account', '{HKD}.accountName',
          '{MOP}.bank', '{MOP}.account', '{MOP}.accountName'].map((n) => `bankAccounts.${n}`)}
      />
      <AttachmentPanel channel={channel} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

      <QR modal={QRModal} />
    </Form>
  );
}

const AttachmentPanel = observer(({ channel, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'view';

  useEffect(() => {
    if (channel.attachments?.length) setIdx(0);
  }, [channel.attachments]);

  const handleAddAttachment = () => {
    if (!channel.attachments) channel.attachments = [];
    channel.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(channel.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    channel.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={7}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(channel.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, model.attachments[0]),
              column('description', {}, model.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`chanel:${channel.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(channel.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              channel.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              channel.attachments[idx]?.binaryId.splice(channel.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(channel.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(ChannelForm);

